import axios from 'axios'
import ErrorResponse from '@/config/error'
import { ElMessage } from 'element-plus'

// 创建请求实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 60 * 1000
})

// request拦截器
service.interceptors.request.use(
  originConfig => {
    const reqConfig = { ...originConfig }
    // 容错处理
    if (!reqConfig.url) {
      console.error('request need url')
      throw new Error({
        source: 'axiosInterceptors',
        message: 'request need url'
      })
    }
    if (!reqConfig.method) {
      // 默认使用 post 请求
      reqConfig.method = 'post'
    }
    // 大小写容错
    reqConfig.method = reqConfig.method.toLowerCase()
    // 参数容错
    if (reqConfig.method === 'get') {
      if (!reqConfig.params) {
        // 防止字段用错
        reqConfig.params = reqConfig.data || {}
      }
    } else if (reqConfig.method === 'post') {
      if (!reqConfig.data) {
        // 防止字段用错
        reqConfig.data = reqConfig.params || {}
      }
      // 检测是否包含文件类型, 若包含则进行 formData 封装
      let hasFile = false
      Object.keys(reqConfig.data).forEach(key => {
        if (typeof reqConfig.data[key] === 'object') {
          const item = reqConfig.data[key]
          if (item instanceof FileList || item instanceof File || item instanceof Blob) {
            hasFile = true
          }
        }
      })
      // 检测到存在文件使用 FormData 提交数据
      if (hasFile) {
        const formData = new FormData()
        Object.keys(reqConfig.data).forEach(key => {
          formData.append(key, reqConfig.data[key])
        })
        reqConfig.data = formData
      }
    } else {
      console.warn(`其他请求类型: ${reqConfig.method}, 暂无自动处理`)
    }
    // const token = getToken()
    // if (token) {
    //     reqConfig.headers.token = token
    // }
    return reqConfig
  },
  error => {
    Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  async res => {
    let { code, msg } = res.data
    const status = res.status.toString()
    if (status.charAt(0) === '5') {
      ElMessage.error('请检查网络是否连接')
      return ErrorResponse.response(res)
    }
    if (status.charAt(0) === '2') {
      if (res.config.handleError) {
        return res.data
      }
      if (code !== 200) {
        ElMessage.error(!msg ? Error.code[999] : msg)
        return ErrorResponse.response(res)
      }
      return res.data
    }
    return new Promise((resolve, reject) => {
      ElMessage.error(msg)
      reject()
    })
  },
  error => {
    console.log(error)
    if (!error.response) {
      ElMessage.error('请检查网络是否异常')
    }

    // 判断请求超时
    if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
      ElMessage.warning('请求超时')
    }
    return Promise.reject(error)
  }
)

// 导出常用函数

/**
 * @param {string} url
 * @param {object} data
 * @param {object} params
 */
export function post(url, data = {}, params = {}) {
  return service({
    method: 'post',
    url,
    data,
    params
  })
}

/**
 * @param {string} url
 * @param {object} params
 */
export function get(url, params = {}) {
  return service({
    method: 'get',
    url,
    params
  })
}

/**
 * @param {string} url
 * @param {object} data
 * @param {object} params
 */
export function put(url, data = {}, params = {}) {
  return service({
    method: 'put',
    url,
    params,
    data
  })
}

/**
 * @param {string} url
 * @param {object} params
 */
export function _delete(url, params = {}) {
  return service({
    method: 'delete',
    url,
    params
  })
}

export default service
